package top.fzqblog.music.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dd.CircularProgressButton;
import com.jakewharton.rxbinding.view.RxView;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.pedant.SweetAlert.SweetAlertDialog;
import top.fzqblog.app.FirstApplication;
import top.fzqblog.firstapp.MainActivity;
import top.fzqblog.firstapp.R;
import top.fzqblog.model.MusicList;
import top.fzqblog.music.adapter.MusicListAdapter;
import top.fzqblog.music.event.PlayEvent;
import top.fzqblog.music.event.ScanEvent;
import top.fzqblog.music.model.Song;
import top.fzqblog.music.util.MusicUtils;
import static top.fzqblog.utils.Constants.TAG;

/**
 * Created by 抽离 on 2017/10/13 0013.
 */

public class ListFragment extends Fragment {

    @BindView(R.id.scanTVContainer)
    public FrameLayout scanTVContainer;

    @BindView(R.id.imageView)
    public ImageView imageView;

    @BindView(R.id.scanTV)
    public TextView textView;

    @BindView(R.id.musicListContainer)
    public RecyclerView musicListContainer;


    MusicListAdapter musicListAdapter;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("demoinfo", "onCreateView: ");
        View view = inflater.inflate(R.layout.music_list_fragment, container, false);;
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onAttach(Context context) {
        //当fragment 第一次与 Activity 产生关联时调用，以后不再调用
        super.onAttach(context);
        Log.d("demoinfo", "Fragment onAttach() 方法执行！");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //在 onAttach 执行完后会立刻调用此方法，通常被用于读取保存的状态值，获取或者初始化一些数据，
        // 但是该方法不执行，窗口是不会显示的，因此如果获取的数据需要访问网络，最好新开线程。
        super.onCreate(savedInstanceState);
        Log.d("demoinfo", "Fragment onCreate() 方法执行！");
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        //在 Activity.onCreate() 方法调用后会立刻调用此方法，表示窗口已经初始化完毕，此时可以调用控件了
        super.onActivityCreated(savedInstanceState);
        initView();
        EventBus.getDefault().register(this);//注册eventbus
        List<Song> songs = MusicUtils.getMusicData(getActivity());
        if(songs==null || songs.size() == 0){
            scanTVContainer.setVisibility(View.VISIBLE);
        }else{
            Log.i(TAG, "onActivityCreated: " + songs);
            scanTVContainer.setVisibility(View.GONE);
            musicListAdapter = new MusicListAdapter(R.layout.music_item, songs);
            musicListAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
            musicListAdapter.isFirstOnly(false);
            musicListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    Song song = songs.get(i);
                    Log.i(TAG, "onItemClick: " + song);
//                    Bitmap bitmap = MusicUtils.getArtwork(getActivity(), song.getId(), song.getAlbumId(), true, true);
                    Bitmap bitmap = MusicUtils.getAlbumArt(getActivity(), song.getAlbumId());
//                    Toast.makeText(getActivity(), "song:" + songs.get(i).getSong(), Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new PlayEvent(song, songs, i, PlayEvent.PlayAction.PLAY));
                }
            });
            musicListContainer.setAdapter(musicListAdapter);
            musicListContainer.setLayoutManager(new LinearLayoutManager(getActivity()));
            Toast.makeText(getActivity(), "本地有"+ songs.size()+"首歌曲", Toast.LENGTH_SHORT).show();
        }
        Log.d("demoinfo", "Fragment onActivityCreated() 方法执行！");
    }

    private void initView() {

    }

    public void scanSD(){
        RxPermissions
                .getInstance(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if(granted){
//                                            List<Song> songs = MusicUtils.getMusicData(getContext());
//                                            new SweetAlertDialog(getActivity(), SweetAlertDialog.SUCCESS_TYPE)
//                                                    .setTitleText("music")
//                                                    .setContentText(songs.toString())
//                                                    .show();
                        new ScanTask().execute("");
                    }
                    else{
                        new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("没有权限")
                                .setContentText("")
                                .show();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ScanEvent scanEvent){
//        Toast.makeText(getActivity(), "收到消息：" + scanEvent.getType().toString(), Toast.LENGTH_SHORT).show();
        musicListContainer.setVisibility(View.GONE);
        scanTVContainer.setVisibility(View.VISIBLE);
        scanSD();
    }

    static List<String> list;

    public static void initMusicList(){
        list = new ArrayList<>();
    }

    public  List<String> searchMp3Infos(File file, String[] ext) {
        Log.i("tag", "searchMp3Infos: " + file.getAbsolutePath());
        if (file != null) {
            if (file.isDirectory()) {
                Message message = Message.obtain();
                message.obj = file.getAbsolutePath();
                handler.sendMessage(message);
                File[] listFile = file.listFiles();
                if (listFile != null) {
                    for (int i = 0; i < listFile.length; i++) {
                        searchMp3Infos(listFile[i], ext);
                    }
                }
            } else {
                String filename = file.getAbsolutePath();
                for (int i = 0; i < ext.length; i++) {
                    if (filename.endsWith(ext[i])) {
                        list.add(filename);
                        MediaScannerConnection.scanFile(FirstApplication.getInstance(), new String[] { file.getAbsolutePath() }, null, null);
                        break;
                    }
                }
            }
        }
        return list;
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG, "handleMessage: " + msg.obj.toString());
            textView.setText("正在扫描："+msg.obj.toString());
        }
    };



    public class ScanTask extends AsyncTask<String, Integer, List<Song>>{

        int i = 0;

        @Override
        protected List<Song> doInBackground(String... strings) {
            List<String> localMusicList = new ArrayList<>();
            String[] ext = { ".mp3" };
            String path = Environment.getExternalStorageDirectory().getPath();
            File file = new File(path);//可以把"//////"这一串都去掉，扫面范围是整个SD卡，我嫌慢，而且扫出来很多...不是我想要的歌曲，最后还是直接写成QQ音乐的下载目录了，其实自己的APP支持下载的话，可以把歌曲下载的指定目录，然后扫描这个指定目录就行了~全局扫描的确不太合适，又不是杀毒..
            Log.i(TAG, "强制扫描之前： " + MusicUtils.getMusicData(FirstApplication.getInstance()));
            MusicUtils.initMusicList();
//            localMusicList = MusicUtils.searchMp3Infos(file,ext);
            initMusicList();
            localMusicList = searchMp3Infos(file, ext);
            SystemClock.sleep(500);
            List<Song> songs = MusicUtils.getMusicData(FirstApplication.getInstance());
//            return localMusicList;
            return songs;
        }

        @Override
        protected void onPostExecute(List<Song> musics) {
            super.onPostExecute(musics);
            textView.setText("扫描完成");
            Log.i(TAG, "扫描之后：" + musics);
            musicListAdapter = new MusicListAdapter(R.layout.music_item, musics);
            musicListAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
            musicListAdapter.isFirstOnly(false);
            musicListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    Song song = musics.get(i);
                    Log.i(TAG, "onItemClick: " + song);
//                    Bitmap bitmap = MusicUtils.getArtwork(getActivity(), song.getId(), song.getAlbumId(), true, true);
                    Bitmap bitmap = MusicUtils.getAlbumArt(getActivity(), song.getAlbumId());
//                    Toast.makeText(getActivity(), "song:" + songs.get(i).getSong(), Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new PlayEvent(song, musics, i, PlayEvent.PlayAction.PLAY));
                }
            });
            musicListContainer.setAdapter(musicListAdapter);
            musicListContainer.setLayoutManager(new LinearLayoutManager(getActivity()));
            scanTVContainer.setVisibility(View.GONE);
            musicListContainer.setVisibility(View.VISIBLE);

//            btnWithText.setProgress(100);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
//            btnWithText.setProgress(values[0]);
        }
    }

    @Override
    public void onStart() {
        //开始执行与控件相关的逻辑代码，如按键点击
        super.onStart();
        Log.d("demoinfo", "Fragment onStart() 方法执行！");
    }

    @Override
    public void onResume() {
        //这是 Fragment 从创建到显示的最后一个回调的方法
        super.onResume();
        Log.d("demoinfo", "Fragment onResume() 方法执行！");
    }

    @Override
    public void onPause() {
        //当发生界面跳转时，临时暂停，暂停时间是 500ms,0.5s后直接进入下面的 onStop 方法
        super.onPause();
        Log.d("demoinfo", "Fragment onPause() 方法执行！");
    }

    @Override
    public void onStop() {
        //当该方法返回时， Fragment 将从屏幕上消失
        super.onStop();
        Log.d("demoinfo", "Fragment onStop() 方法执行！");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d("demoinfo", "Fragment onSaveInstanceState() 方法执行！");
        outState.putString("myinfo", "haha");
    }

    @Override
    public void onDestroyView() {
        //当 fragment 状态被保存，或者从回退栈弹出，该方法被调用
        super.onDestroyView();
        Log.d("demoinfo", "Fragment onDestroyView() 方法执行！");
    }

    @Override
    public void onDestroy() {
        //当 Fragment 不再被使用时，如按返回键，就会调用此方法
        super.onDestroy();
        EventBus.getDefault().unregister(this);//注册eventbus
        Log.d("demoinfo", "Fragment onDestroy() 方法执行！");
    }

    @Override
    public void onDetach() {
        //Fragment 生命周期的最后一个方法，执行完后将不再与 Activity 关联，将释放所有 fragment 对象和资源
        super.onDetach();
        Log.d("demoinfo", "Fragment onDetach() 方法执行！");
    }
}
